<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请输入SPU名称"
        v-model="SpuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          v-for="(item, index) in TradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type=""
        placeholder="请输入SPU描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        list-type="picture-card"
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <!-- v-model:fileList->展示默认图片 
                 action:上传图片的接口地址
                 list-type:文件列表的类型
            -->
      <el-dialog v-model="dialog">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select
        v-model="saleAttrIdName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还有${unSelectSaleAttr.length}个未选择`
            : '无'
        "
      >
        <el-option
          :value="`${item.id}:${item.name}`"
          :label="item.name"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
        ></el-option>
      </el-select>
      <el-button
        :disabled="saleAttrIdName ? false : true"
        type="primary"
        icon="Plus"
        style="margin-left: 10px"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
    </el-form-item>
    <el-form-item>
      <el-table border style="margin: 10px 0" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          label="销售属性名"
          width="100"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 0px 5px"
              v-for="(item, index) in row.spuSaleAttrValueList"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              :key="index"
              class="mx-1"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag == true"
              placeholder="请你输入属性值"
              size="small"
              style="width: 100px"
              v-model="row.saleAttrValue"
              @blur="toLook(row)"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toAdd(row)"
            ></el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="save"
        :disabled="saleAttr.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import type { SpuData } from '@/api/product/spu/type'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'
import type {
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  SaleAttr,
  SaleAttrValue,
} from '@/api/product/spu/type'
import { ElMessage } from 'element-plus'
// import { reqAddOrUpdateAttr } from '@/api/product/attr'
let emit = defineEmits(['changeScene'])
const cancel = () => {
  emit('changeScene', { flag: 0, params: 'update' })
}

//存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: '', //收集三级分类的ID
  spuName: '', //SPU的名字
  description: '', //SPU的描述
  tmId: '', //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})
//所有品牌数据
let TradeMark: any = ref([])
//所有图片数据
let imgList: any = ref([])
// spu已有销售属性
let saleAttr: any = ref([])
// 所有的销售属性
let allSaleAttr: any = ref([])
// 收集还未选择的销售属性和id
let saleAttrIdName: any = ref([])
const initHasSpuData = async (spu: SpuData) => {
  SpuParams.value = spu
  let res: AllTradeMark = await reqAllTradeMark()
  let res1: SpuHasImg = await reqSpuImageList(spu.id as number)
  let res2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  let res3 = await reqAllSaleAttr()
  TradeMark.value = res.data
  imgList.value = res1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  console.log('res2.data', res2.data)
  // saleAttr.value = res2.data
  allSaleAttr.value = res3.data
}
// 供父组件调用的初始化SPU函数
const initAddSpu = async (c3ID: string | number) => {
  //在添加点击按钮时清除表单里原有的数据
  Object.assign(SpuParams.value, {
    category3Id: '', //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  // 照片墙和销售属性清空
  imgList.value = ''
  saleAttr.value = []
  saleAttrIdName.value = ''
  SpuParams.value.category3Id = c3ID
  let res1 = await reqAllTradeMark()
  let res2 = await reqAllSaleAttr()
  TradeMark.value = res1.data
  allSaleAttr.value = res2.data
}
//子组件的方法对外暴露，让父组件可以使用
defineExpose({ initHasSpuData, initAddSpu })
// 预览对话框是否显示
let dialog = ref<boolean>(false)
//预览图片地址
let dialogImageUrl: any = ref('')
// 照片墙预览(图片的➕)
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialog.value = true
}
//照片墙删除图片的钩子
const handleRemove = (file: any) => {
  // dialogImageUrl.value = file.url
  // dialog.value = true
}
let unSelectSaleAttr = computed(() => {
  let unSelect = allSaleAttr.value.filter((item: any) => {
    return saleAttr.value.every((item1: any) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelect
})

const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdName.value.split(':')
  // const az = saleAttrIdName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  saleAttr.value.push(newSaleAttr)
  saleAttrIdName.value = '' //清空select显示的
}

const toAdd = (row: SaleAttr) => {
  row.flag = true
  //动态向该saleAttr中添加一个saleAttrValue这个属性值，
  row.saleAttrValue = ''
}

const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  // 追加前的判断
  if (saleAttrValue?.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  } //属性值为空
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  // 追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.saleAttrValue = ''
  row.flag = false
}
// 编辑的保存按钮
const save = async () => {
  SpuParams.value.spuImageList = imgList.value.map((item) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  SpuParams.value.spuSaleAttrList = saleAttr.value
  let res = await reqAddOrUpdateSpu(SpuParams.value)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
</script>

<style></style>
